package com.example.administrator.test.login;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.test.MainActivity;
import com.example.administrator.test.R;
import com.example.administrator.test.login.bean.MatchCodeSendBean;
import com.example.administrator.test.login.bean.MatchCodeTurnBean;
import com.google.gson.Gson;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.GsonConverterFactory;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 输入验证码界面
 */
public class CodeActivity extends AppCompatActivity {
    private static String token;
    private EditText mFirstEditText,mSecondEditText,mThreadEditText,mFouthEditText;
    private Button mLogin;
    private TextView textView;
    private String phone;
    private MatchCodeTurnBean mTurnMatchCodeBean;
    private SQLiteDatabase db;
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verificationcode);
        //四个文本输入框，用来放置四位验证码
        mFirstEditText = (EditText) findViewById(R.id.VCode_first_number);
        mSecondEditText= (EditText) findViewById(R.id.VCode_second_number);
        mThreadEditText= (EditText) findViewById(R.id.VCode_thread_number);
        mFouthEditText= (EditText) findViewById(R.id.VCode_fourth_number);
        mLogin= (Button) findViewById(R.id.VCode_login);
        final EditText[] mEditTextArray=new EditText[]{mFirstEditText,mSecondEditText,mThreadEditText,mFouthEditText};
        for (int i = 0; i < mEditTextArray.length; i++) {
            final int j = i;
            mEditTextArray[j].addTextChangedListener(new TextWatcher() {
                private CharSequence temp;
                private int sStart;
                private int sEnd;

                @Override
                public void onTextChanged(CharSequence s, int start,
                                          int before, int count) {
                    temp = s;
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                                              int count, int after) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    sStart = mEditTextArray[j].getSelectionStart();
                    sEnd = mEditTextArray[j].getSelectionEnd();

                    if (temp.length() == 1 && (j == 0 || j == 1 || j == 2)) {
                        mEditTextArray[j + 1].setFocusable(true);
                        mEditTextArray[j + 1].setFocusableInTouchMode(true);
                        mEditTextArray[j + 1].requestFocus();
                    }
                    if (mEditTextArray[j].length()==0 && j>=1) {
                        mEditTextArray[j - 1].setFocusable(true);
                        mEditTextArray[j - 1].setFocusableInTouchMode(true);
                        mEditTextArray[j - 1].requestFocus();
                    }
                    if (temp.length() > 1) {

                        s.delete(sStart - 1, sEnd);
                        int tSelection = sStart;
                        mEditTextArray[j].setText(s);
                        mEditTextArray[j].setSelection(tSelection);
                    }
                }
            });
        }
        Intent intent=getIntent();
        phone=intent.getStringExtra("phone");
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MatchCodeSendBean sendMatchCodeBean=new MatchCodeSendBean();
                sendMatchCodeBean=initSendMatchCodeBean(sendMatchCodeBean);
                Gson gson=new Gson();
                String route=gson.toJson(sendMatchCodeBean);
                Retrofit retrofit=new Retrofit.Builder()
                        .baseUrl(Constant.BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                PostRoute postRoute=retrofit.create(PostRoute.class);
                RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
                Call<MatchCodeTurnBean> call=postRoute.getTurnMatchCode(body);
                call.enqueue(new Callback<MatchCodeTurnBean>() {
                    @Override
                    public void onResponse(Call<MatchCodeTurnBean> call, Response<MatchCodeTurnBean> response) {
                        mTurnMatchCodeBean=response.body();
                        token=mTurnMatchCodeBean.getToken();
                        String resultCode=mTurnMatchCodeBean.getVerificationState();
                        if (resultCode!=null && resultCode.equals("0")){//判断后台返回验证码匹配状态
                            //匹配正确后将登录密匙及手机号码保存到数据库
                            db = helper.getWritableDatabase();
                            db.execSQL("insert into records(token) values('" + token + "')");//将登录密匙存入数据库
                            db.execSQL("insert into records(phone) values('" + phone + "')");//将手机号码存入数据库
                            db.close();
                            //匹配正确后跳转到主界面
                            Intent intentMainActivity=new Intent(CodeActivity.this,MainActivity.class);
                            startActivity(intentMainActivity);
                        }else {
                            Toast.makeText(CodeActivity.this,"验证码输入有误", Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onFailure(Call<MatchCodeTurnBean> call, Throwable t) {

                    }
                });
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        finish();
    }

    private MatchCodeSendBean initSendMatchCodeBean(MatchCodeSendBean sendMatchCodeBean){
        sendMatchCodeBean.setPhone(phone);
        sendMatchCodeBean.setOperType("2002");
        sendMatchCodeBean.setVerificationCode(mFirstEditText.getText().toString()
                +mSecondEditText.getText().toString()
                +mThreadEditText.getText().toString()
                +mFouthEditText.getText().toString());
        return sendMatchCodeBean;
    }
    public static String getToken(){
        return token;
    }
}
